#include "udiskexport.h"
#include "diskmanager.h"
#include "authmanager.h"
#include "commonfunction.h"
#include "udisk.h"
#include <QThread>
#include <QMap>
#include <QPixmap>

class UdiskExportPrivate : public QThread
{
    Q_OBJECT
public:
    UdiskExportPrivate(IDataExport *parent) : QThread(parent), m_parent(parent) {}
    void exports(ReportType type, IExportable *exporter);

protected:
    void run();
    bool saveToFile(const QString &filename);

private:
    ReportType m_type;
    IDataExport *m_parent;
    IExportable *m_exporter;
};

UdiskExport::UdiskExport(QObject *parent) : IDataExport(parent), d(new UdiskExportPrivate(this))
{
}

UdiskExport::~UdiskExport()
{
    d->quit();
    d->wait();
    d->deleteLater();
}

void UdiskExport::exports(ReportType type, IExportable *exportImpl)
{
    d->exports(type, exportImpl);
}

void UdiskExportPrivate::exports(ReportType type, IExportable *exporter)
{
    m_type = type;
    m_exporter = exporter;
    QThread::start();
}

void UdiskExportPrivate::run()
{
    static const QMap<ReportType, const char *> mapper = {
        { LOG_REPORT, "Log" },
        { DATA_REPROT, "Data" },
        { PERF_VOLT_REPORT, "Volt" },
        { PERF_FLOW_REPORT, "Flow" },
        { PRINT_TEPLATE_REPORT, "Template" },
        { EXPERIMENT_REPORT, "Report" },
        { FACTORY_DATA, "factory" }
    };

    Udisk disk(UsbMountDir);
    if (!disk.mount())
    {
        emit m_parent->done(disk.error());
        return;
    }

    bool ret = true;
    QString prefix = mapper.contains(m_type) ? mapper[m_type] : "Undefined";
    QString exportDir = UsbRootDir + prefix + "/";
    QString filename = generateFileName(exportDir, prefix, "pdf");

    // 创建目录
    ret = ret && DiskManager::mkdir(UsbMountDir);
    ret = ret && DiskManager::mkdir(UsbRootDir);
    ret = ret && DiskManager::mkdir(exportDir);

    // 导出pdf
    ret = ret && saveToFile(filename);

    QString filepath = ret ? filename.replace(UsbMountDir, "") : "";
    QString message = ret ? tr("Exported Success.") : tr("Exported Fail.");
    emit m_parent->done(message, filepath);
}

bool UdiskExportPrivate::saveToFile(const QString &filename)
{
    m_exporter->save(filename);
    return DiskManager::fileExists(filename);
}

#include "udiskexport.moc"
